package dev.dworks.apps.alauncher.helpers;

import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;

import com.android.launcher3.Utilities;

import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

import androidx.annotation.Nullable;

public class SecurityHelper {
    public static final String TAG = "SecurityHelper";
    private static final String KEY_NAME = "test";
    public static final int REQUEST_CONFIRM_CREDENTIALS = 1212;

    private final String mToBeSignedMessage;
    private final KeyguardManager mKeyguardManager;

    public Activity mActivity;

    public interface SecurityCallback {
        void onActivityResult(int requestCode, int resultCode, Intent data);
    }

    public SecurityHelper(Activity activity){
        mActivity = activity;
        mKeyguardManager = (KeyguardManager) mActivity.getSystemService(Context.KEYGUARD_SERVICE);
        // Init signature
        Signature signature;
        try {
            // Send key name and challenge to the server, this message will be verified with registered public key on the server
            mToBeSignedMessage = new StringBuilder()
                    .append(KEY_NAME)
                    .append(":")
                    // Generated by the server to protect against replay attack
                    .append("12345")
                    .toString();
            signature = initSignature(KEY_NAME);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Nullable
    private KeyPair getKeyPair(String keyName) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        if (keyStore.containsAlias(keyName)) {
            // Get public key
            PublicKey publicKey = keyStore.getCertificate(keyName).getPublicKey();
            // Get private key
            PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyName, null);
            // Return a key pair
            return new KeyPair(publicKey, privateKey);
        }
        return null;
    }

    @Nullable
    private Signature initSignature (String keyName) throws Exception {
        KeyPair keyPair = getKeyPair(keyName);

        if (keyPair != null) {
            Signature signature = Signature.getInstance("SHA256withECDSA");
            signature.initSign(keyPair.getPrivate());
            return signature;
        }
        return null;
    }

    public boolean isDeviceSecure(){
        if(Utilities.ATLEAST_MARSHMALLOW){
            return mKeyguardManager.isDeviceSecure();
        } else {
            return mKeyguardManager.isKeyguardSecure();
        }
    }

    public void authenticate(String title, String description){
        if (isDeviceSecure()) {
            Intent intent = mKeyguardManager.createConfirmDeviceCredentialIntent(title, description);
            if (intent != null) {
                mActivity.startActivityForResult(intent, REQUEST_CONFIRM_CREDENTIALS);
            }
        }
    }

    public void authenticate(){
        authenticate(null, null);
    }
}
